<?php
/**
 * KidsMind Cognitive Modules API
 * 
 * This file provides API endpoints for fetching cognitive module data from the database
 * 
 * Available endpoints:
 * - /api/cognitive.php?action=categories&age=3-4
 * - /api/cognitive.php?action=module&slug=colors&age=3-4
 * - /api/cognitive.php?action=items&module=colors&age=3-4
 */

// Set headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

// Include database connection file
require_once '../include/db.php';

// Get action from request
$action = isset($_GET['action']) ? $_GET['action'] : '';
$age = isset($_GET['age']) ? $_GET['age'] : '3-4'; // Default to 3-4 age group

// Validate age
$valid_ages = ['3-4', '5-6', '7-8', 'all'];
if (!in_array($age, $valid_ages)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid age group']);
    exit;
}

// Process the requested action
switch ($action) {
    case 'categories':
        // Get all categories for specified age group
        getCategoriesByAge($age);
        break;
    
    case 'modules':
        // Get all modules for a category
        $category = isset($_GET['category']) ? $_GET['category'] : '';
        if (empty($category)) {
            http_response_code(400);
            echo json_encode(['error' => 'Category slug is required']);
            exit;
        }
        getModulesByCategory($category, $age);
        break;
    
    case 'module':
        // Get a specific module by slug
        $slug = isset($_GET['slug']) ? $_GET['slug'] : '';
        if (empty($slug)) {
            http_response_code(400);
            echo json_encode(['error' => 'Module slug is required']);
            exit;
        }
        getModuleBySlug($slug, $age);
        break;
    
    case 'items':
        // Get items for a specific module
        $module = isset($_GET['module']) ? $_GET['module'] : '';
        if (empty($module)) {
            http_response_code(400);
            echo json_encode(['error' => 'Module slug is required']);
            exit;
        }
        getItemsByModule($module, $age);
        break;
    
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        exit;
}

/**
 * Get all categories for a specific age group
 * 
 * @param string $age Age group (3-4, 5-6, 7-8, all)
 */
function getCategoriesByAge($age) {
    global $conn;
    
    try {
        $sql = "SELECT id, name, slug, description, icon, thumbnail, color_hex, 
                       header_color_hex, bg_gradient_start, bg_gradient_end, display_order
                FROM km_cognitive_categories 
                WHERE (age_group = ? OR age_group = 'all') 
                AND is_active = 1
                ORDER BY display_order ASC";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('s', $age);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $categories = [];
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
        
        echo json_encode(['status' => 'success', 'data' => $categories]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

/**
 * Get all modules for a specific category and age group
 * 
 * @param string $categorySlug Category slug
 * @param string $age Age group (3-4, 5-6, 7-8, all)
 */
function getModulesByCategory($categorySlug, $age) {
    global $conn;
    
    try {
        $sql = "SELECT m.id, m.name, m.slug, m.description, m.introduction,
                       m.color_hex, m.icon, m.thumbnail, m.is_premium, m.display_order
                FROM km_cognitive_modules m
                JOIN km_cognitive_categories c ON m.category_id = c.id
                WHERE c.slug = ? 
                AND (c.age_group = ? OR c.age_group = 'all')
                AND m.is_active = 1
                ORDER BY m.display_order ASC";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ss', $categorySlug, $age);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $modules = [];
        while ($row = $result->fetch_assoc()) {
            $modules[] = $row;
        }
        
        echo json_encode(['status' => 'success', 'data' => $modules]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

/**
 * Get a specific module by slug
 * 
 * @param string $moduleSlug Module slug
 * @param string $age Age group (3-4, 5-6, 7-8, all)
 */
function getModuleBySlug($moduleSlug, $age) {
    global $conn;
    
    try {
        $sql = "SELECT m.id, m.name, m.slug, m.description, m.introduction,
                       m.color_hex, m.icon, m.thumbnail, m.is_premium, 
                       c.name as category_name, c.slug as category_slug
                FROM km_cognitive_modules m
                JOIN km_cognitive_categories c ON m.category_id = c.id
                WHERE m.slug = ? 
                AND (c.age_group = ? OR c.age_group = 'all')
                AND m.is_active = 1";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ss', $moduleSlug, $age);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            http_response_code(404);
            echo json_encode(['error' => 'Module not found']);
            exit;
        }
        
        $module = $result->fetch_assoc();
        
        // Get items count
        $sql = "SELECT COUNT(*) as total_items
                FROM km_cognitive_items
                WHERE module_id = ? AND is_active = 1";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $module['id']);
        $stmt->execute();
        $itemsResult = $stmt->get_result();
        $itemsData = $itemsResult->fetch_assoc();
        
        $module['total_items'] = $itemsData['total_items'];
        
        echo json_encode(['status' => 'success', 'data' => $module]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}

/**
 * Get all items for a specific module
 * 
 * @param string $moduleSlug Module slug
 * @param string $age Age group (3-4, 5-6, 7-8, all)
 */
function getItemsByModule($moduleSlug, $age) {
    global $conn;
    
    try {
        $sql = "SELECT i.id, i.name, i.description, i.content, i.additional_info,
                       i.image_path, i.display_order
                FROM km_cognitive_items i
                JOIN km_cognitive_modules m ON i.module_id = m.id
                JOIN km_cognitive_categories c ON m.category_id = c.id
                WHERE m.slug = ? 
                AND (c.age_group = ? OR c.age_group = 'all')
                AND i.is_active = 1
                ORDER BY i.display_order ASC";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ss', $moduleSlug, $age);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $items = [];
        while ($row = $result->fetch_assoc()) {
            $items[] = $row;
        }
        
        echo json_encode(['status' => 'success', 'data' => $items]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
} 